import {CollapsibleEntry, ListEntry} from "@bpmn-io/properties-panel";
import {getBusinessObject} from "bpmn-js/lib/util/ModelUtil";
import {getFormFields} from '@/api/BusinessForDesignApi'
import {useService} from "bpmn-js-properties-panel";
import {jsx} from "@bpmn-io/properties-panel/preact/jsx-runtime";

const component = {
  id: 'formFieldList',
  component: FormFieldList,
  shouldOpen:true
}

if(window['register']) {
  window['register'].regComponent(component.id,component)
}

export default function(element) {
  component['element']=element;
  return component;
}
function FormFieldList(props) {
  const { element, id,register,property,defaultFormAuthValue } = props;
  const bpmnFactory = useService('bpmnFactory');
  const commandStack = useService('commandStack');
  const translate = useService('translate');
  const propertyBusinessObject =  getBusinessObject(property);
  if(propertyBusinessObject) {
    const value = propertyBusinessObject.get('value')
    if(value) {
      let temp = eval('('+value+')')
      // 远程查询表单字段列表
      let respones = getFormFields(temp.id,temp.type);
      if(respones){
        return jsx(ListEntry, {
          id: id,
          register: register,
          translate: translate,
          element: element,
          label: translate('FormAuthFields'),
          items: respones,
          component: FieldAuth,
          formData:temp,
          showAdd:false,
          defaultFormAuthValue,
          autoFocusEntry: true,
          shouldOpen:true,
          open:true
        });
      }
    }
  }
}
function FieldAuth(props) {
  const {
    element,
    id,
    index,
    formData,
    item: field,
    open,
    register,
    defaultFormAuthValue
  } = props;
  const fieldId = `${id}-field-${index}`;
  return jsx(CollapsibleEntry, {
    id: fieldId,
    element: element,
    entries: FieldInjection({
      element,
      field,
      register,
      formData,
      defaultFormAuthValue,
      idPrefix: fieldId
    }),
    label: field.name || '<empty>',
    open: true,
    shouldOpen:true
  });
}

function FieldInjection(props) {
  const {
    element,
    idPrefix,
    field,
    formData,
    register,
    translate,
    defaultFormAuthValue
  } = props;
  let arrs = ['formFieldAuth'];
  const list = []
  for (let i = 0; i < arrs.length; i++) {
    let entries = register.findEntries(arrs[i],translate)
    entries = {...entries}
    entries.id = idPrefix+"_"+arrs[i];
    entries.element =element;
    entries.field =field;
    entries.idPrefix =idPrefix;
    entries.property=field
    entries.filedName=field.id
    entries.formData=formData
    entries.defaultFormAuthValue=defaultFormAuthValue
    list.push(entries)
  }
  return list;
}
